package com.yuanfeng.commoms.exception;


import com.yuanfeng.commoms.util.ResponseResult;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.security.sasl.AuthenticationException;
import javax.validation.ValidationException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 全局的的异常拦截器（拦截所有的控制器）
 */
@RestControllerAdvice
@Order(-1)
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 所有异常信息
     *
     * @param exception
     * @return
     * @throws Exception
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.class)
    public ResponseResult<?> exceptionHandler(Exception exception) {
        log.error("exceptionHandle [{}]", exception.toString());
        if (exception instanceof LoginToException){
            exception.printStackTrace();
            return ResponseResult.fail(((LoginToException) exception).getMessageCode(), exception.getMessage());
        }
        exception.printStackTrace();
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(), exception.getMessage());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ResponseResult<?> handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return ResponseResult.fail(GlobalExceptionEnum.MYSQL_EXCEPTION_DATA_DUPLICATION.getErrorCode(),GlobalExceptionEnum.MYSQL_EXCEPTION_DATA_DUPLICATION.getErrorMsg());
    }

    @ExceptionHandler(AuthenticationException.class)
    public ResponseResult<?> authenticationExceptionException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
    }

    @ExceptionHandler(value = DefinedException.class)
    public ResponseResult<String> baseExceptionHandler(DefinedException e) {
        log.error("发生业务异常！原因是：[{}]", e.getMessage());
        return ResponseResult.fail(e.getMessageCode(), e.getMessage());
    }

    @ExceptionHandler(ExpiredJwtException.class)
    public ResponseResult<?> expiredJwtException(DuplicateKeyException e) {
        log.error(e.getMessage(), e);
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        List<Map<String, Object>> list = new ArrayList<>();
        List<FieldError> errorList = e.getBindingResult().getFieldErrors();
        errorList.forEach(fieldError -> {
            Map<String, Object> map = new HashMap<>();
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
            list.add(map);
        });
        return ResponseResult.fail(list);
    }

    //自定义校验报错
    @ExceptionHandler(ValidationException.class)
    public ResponseResult<?> validationException(ValidationException e) {
        log.error(e.getMessage(), e);
        return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg());
    }

}
